package com.hfzy.ihk.web.file_upload.controller;

import com.hfzy.ihk.common.constants.GlobalStatic;
import com.hfzy.ihk.common.util.FileUtils;
import com.hfzy.ihk.common.util.Utils;
import com.hfzy.ihk.common.util.string.StringUtil;
import com.hfzy.ihk.common.web.WebResult;
import com.hfzy.ihk.web.file_upload.enums.UploadRecordFileType;
import com.hfzy.ihk.web.file_upload.support.DefaultResult;
import com.hfzy.ihk.web.file_upload.support.HttpsClientRequestFactory;
import com.hfzy.ihk.web.file_upload.support.RecordsPath;
import com.hfzy.ihk.web.file_upload.utils.WebResultUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;



/**
 * @Auther: Administrator
 * @Date: 2019/4/23 10:54
 * @Description:
 * @author zp
 */
@RequestMapping("/api/record")
@Controller
@ResponseBody
public class RecordsUploadController {

    @Value("${web.upload_path}")
    private String uploadPath;

    @Value("${web.record_file_url}")
    private String recordFileUrl;

    @Value("${web.target_url}")
    private  String targetUrl;


    Logger logger = LoggerFactory.getLogger(RecordsUploadController.class);


    @RequestMapping("test")
    @ResponseBody
    public ModelAndView test(){
        ModelAndView mv = new ModelAndView();
        mv.setViewName("index");
        return mv;
    }


    //上传录音到话术的接口 --- 小程序一次只可以上传一条录音--》因此加上index标识上传哪条回答的录音 --》目前上传接口 仅处理单个录音
    @ResponseBody
    @RequestMapping("uploadRecordFile")
    @CrossOrigin
    public DefaultResult uploadRecordFile(HttpServletRequest request,String uploadType,String id,String index){
        logger.info("uploadRecordFile:{}{}{}",uploadType,id,index);

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Iterator<String> list = multipartRequest.getFileNames();
        DefaultResult defaultResult = WebResultUtils.getFailCharDefaultResulte("");
        UploadRecordFileType uploadRecordFileType = UploadRecordFileType.fromValue(uploadType);
        int fileNum = 0;
        LinkedList<String> fileUrlList = new LinkedList<String>();
        LinkedList<String> realFileNameList = new LinkedList<String>();
        RestTemplate restTemplate = new RestTemplate(new HttpsClientRequestFactory());
        //硬盘路径
        String hardPath = "";
        String firstPath= "";
        logger.info("iterator:{}",list.hasNext());
        try {
            while (list.hasNext()){
                //获取当前的时间毫秒值来进行随机存储到一个硬盘中
                Long currentTime = System.currentTimeMillis();
                if (currentTime % 2 == 0){
                    // cloudcall_file/rec_20050/wxRecordFile/
                    hardPath = RecordsPath.recordsPathOne;
                    firstPath = uploadPath+hardPath;
                }else {
                    hardPath = RecordsPath.recordsPathTwo;
                    firstPath = uploadPath+hardPath;
                }
                fileNum++;
                String fileName  = list.next();
                if(fileName!=null){
                    MultipartFile voiceFile = multipartRequest.getFile(fileName);//语音文件
                    fileName = voiceFile.getOriginalFilename();
                    //*window下则在指定盘下，linux则在根目录下*//*
                    String line=File.separator;
                    File filePath = new File(firstPath);
                    if (!filePath.exists()) {
                        boolean isMkDir = filePath.mkdirs();
                        if (isMkDir == false){
                            logger.info("文件夹创建失败");
                            throw new Exception("文件夹创建失败");
                        }
                    }

                    if (voiceFile!=null && !voiceFile.isEmpty()) {
                        String lastName = voiceFile.getOriginalFilename().substring(voiceFile.getOriginalFilename().lastIndexOf("."), voiceFile.getOriginalFilename().length()).toLowerCase();

                        if (lastName.indexOf("amr") == -1 && lastName.indexOf("mp3") == -1) {
                            logger.info("附件格式错误");
                            defaultResult = WebResultUtils.getFailCharDefaultResulte("附件格式错误");
                        } else {
                            try {
                                //存在文件
                                if (voiceFile.getSize() > 0) {
                                    //上传音频文件
                                    String recordType = "OUT";
                                    String type = lastName.indexOf("amr")!=-1?"amr":(lastName.indexOf("mp3")!=-1?"mp3":"");
                                    String realFileName = fileName.substring(0,fileName.lastIndexOf("."));
                                    //String testPath = "D:\\ceshi";
                                    String fileSaveBasePath0 = filePath+recordFileUrl+line+ recordType+line+type+line+Utils.date2String(new Date(),"yyyyMMdd");

                                    String savePath = FileUtils.uploadFile(voiceFile,realFileName,fileSaveBasePath0,type);
                                    String serverName = request.getServerName();

                                    logger.info("保存成功，文件保存路径：{}",savePath);
                                    //访问录音的路径 https://www.ihk.cn:8882/recordsUpload/RecordFileUrl/rec_20050/wxRecordFile/RecordFileUrl/OUT/mp3/20190515/ceshi.mp3
                                    String urlPath = StringUtil.strConnect(recordFileUrl,hardPath,"RecordFileUrl","/"
                                            ,recordType,"/",type,"/",Utils.date2String(new Date(),"yyyyMMdd")+"/"+fileName);
                                    String recordFileUrl = ("https://" + serverName + ":" +request.getServerPort()+request.getContextPath() + urlPath);
                                    logger.info("branch up file url:{}",recordFileUrl);
                                    realFileNameList.add(realFileName);
                                    fileUrlList.add(recordFileUrl);

                                    //有文件情况下===进行更新操作
                                    if(fileNum>0 && fileUrlList.size() == fileNum){
                                        switch (uploadRecordFileType){
                                            case SPEAKINGFLOWSTEP:
                                                //拼接接口url
                                                String speakingFlowStepUrl = StringUtil.strConnect(targetUrl,"/flowConfig","/updateFlowStepRecordFileUrl");
                                                speakingFlowStepUrl = processingParameter(speakingFlowStepUrl,id,null,recordFileUrl);
                                                WebResult webResult = restTemplate.getForObject(speakingFlowStepUrl, WebResult.class);

                                                if (GlobalStatic.EXCEPTION_CHAR.equals(webResult.getCode()) || GlobalStatic.CODE_N.equals(webResult.getMsg())){
                                                    defaultResult.setMsg("文件上传失败");
                                                }
                                                break;
                                            case KNOWLEDGE:
                                                //拼接接口url
                                                String knowLeDegUrl = StringUtil.strConnect(targetUrl,"/knowledgeBase","/updateKnowledgeBaseResultVo");
                                                knowLeDegUrl = processingParameter(knowLeDegUrl,id,index,recordFileUrl);
                                                WebResult webResult1 = restTemplate.getForObject(knowLeDegUrl, WebResult.class);
                                                if (GlobalStatic.EXCEPTION_CHAR.equals(webResult1.getCode()) || GlobalStatic.CODE_N.equals(webResult1.getMsg())){
                                                    defaultResult.setMsg("文件上传失败");
                                                }
                                                break;
                                            default:
                                                break;
                                        }
                                    }
                                    defaultResult= WebResultUtils.getSuccessCharDefaultResulte("文件上传成功",null);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                defaultResult = WebResultUtils.getFailCharDefaultResulte("附件格式错误");
                                logger.info("附件格式错误");
                            }
                        }
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            defaultResult = WebResultUtils.getExceptionCharDefaultResulte("操作异常,"+e.getMessage());
        }
        return defaultResult;
    }

    /**
     *  处理接口参数方法
     * @param url 请求地址
     * @param id 在es中的_id
     * @param index
     * @param recordFileUrl 录音存储的url
     * @return
     */
    public String processingParameter(String url,String id,String index,String recordFileUrl){
        StringBuilder stringBuilder = new StringBuilder(url);
        stringBuilder.append("?id="+id);
        stringBuilder.append("&recordFileUrl="+recordFileUrl);
        if (index != null){
            stringBuilder.append("&resultId="+index);
        }
        return stringBuilder.toString();
    }
}
